package cart

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
	"ttsx/server/utils"
)

func AddCart(ctx *gin.Context) { // 购物车的增加
	// 获取cookies中的uid
	uid := ctx.GetInt("uid")
	Name := ctx.GetString("username")
	if Name == "" {
		ctx.JSON(http.StatusOK, map[string]interface{}{"Code": -1, "errMsg": "请您先登录"})
		return
	}

	// 获取前端提交的数据
	sku_id := ctx.PostForm("sku_id")
	count := utils.StrToInt(ctx.PostForm("count"))
	global.App.Log.Sugar().Infof("uid: %d,sku_id: %s, count: %s", uid, sku_id, count)

	// 校验数据
	var NewGoodsSKU model.GoodsSKU
	if ret := global.App.DB.Where("id = ?", sku_id).Find(&NewGoodsSKU); ret.RowsAffected == 0 {
		ctx.JSON(http.StatusOK, map[string]interface{}{"Code": 1, "errMsg": "商品不存在"})
		return
	}
	global.App.Log.Sugar().Infof("uid: %d, NewGoodsSKU: %v", uid, NewGoodsSKU)

	// 根据uid查询redis中对应用户是否已经添加相同商品
	// 如果没有，则新增. 如果有，则商品数量相加
	cartKey := fmt.Sprintf("cartKey_%d", uid)
	cartCount, _ := global.App.RDB.HGet(ctx, cartKey, sku_id).Result()

	if cartCount != "" {
		count = utils.StrToInt(cartCount) + count
	}
	global.App.Log.Sugar().Infof("uid: %d, cartKey: %s, cartCount: %s", uid, cartKey, cartCount)

	// 如果购物车里的商品数量超过库存，则弹出库存不足
	if count > NewGoodsSKU.Stock {
		ctx.JSON(http.StatusOK, map[string]interface{}{"Code": 2, "errMsg": "商品库存不足"})
		return
	}

	// 添加商品
	global.App.RDB.HSet(ctx, cartKey, sku_id, count).Result()
	global.App.Log.Sugar().Infof("uid: %d 添加商品到购物车成功", uid)

	// 根据sku_id获取购物车中的种类数，返回给前端跟新购物车图标上的数目
	cartNum, _ := global.App.RDB.HLen(ctx, cartKey).Result()

	ctx.JSON(http.StatusOK, map[string]interface{}{"Code": 3, "cartNum": cartNum, "Msg": "商品添加成功"})
}

func SelectCart(ctx *gin.Context) { // 购物车的查询
	// 获取cookies中的用户信息
	uid := ctx.GetInt("uid")
	Name := ctx.GetString("username")
	IsActive := ctx.GetBool("IsActive")

	// 根据uid拼接cartKey,并查询数量
	cartKey := fmt.Sprintf("cartKey_%d", uid)
	cartMap, _ := global.App.RDB.HGetAll(ctx, cartKey).Result()
	global.App.Log.Sugar().Infof("uid: %d, cartKey: %s, cartMap: %v", uid, cartKey, cartMap)

	var totalCount int = 0
	var totalPrice float64 = 0
	var goods []map[string]interface{}

	for sku_id, count := range cartMap {
		// 根据sku_id 查询GoodsSKU表
		var NewGoodsSKU map[string]interface{}
		global.App.DB.Model(&model.GoodsSKU{}).
			Select("id", "name", "price", "unite", "image").
			Where("id = ?", sku_id).
			Scan(&NewGoodsSKU)
		global.App.Log.Sugar().Infof("uid: %d, NewGoodsSKU: %v", uid, NewGoodsSKU)

		// 商品数量
		NewGoodsSKU["count"] = utils.StrToInt(count)

		// 商品小计
		price := NewGoodsSKU["price"].(string)
		floatPrice, _ := strconv.ParseFloat(price, 64)
		subPrice, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", float64(utils.StrToInt(count))*floatPrice), 64)
		NewGoodsSKU["subPrice"] = subPrice

		// 获取总数量 和 总价格
		totalCount = totalCount + utils.StrToInt(count)
		totalPrice = totalPrice + subPrice

		goods = append(goods, NewGoodsSKU)
	}
	global.App.Log.Sugar().Infof("uid: %d, goods: %v", uid, goods)

	ctx.HTML(http.StatusOK, "cart/cart.html", map[string]interface{}{
		"Name":       Name,
		"IsActive":   IsActive,
		"totalCount": totalCount,
		"totalPrice": totalPrice,
		"goods":      goods,
	})
}

func UpdateCart(ctx *gin.Context) { // 购物车的更新
	// 获取uid
	uid := ctx.GetInt("uid")

	// 获取ajax提交的数据
	sku_id := ctx.PostForm("sku_id")
	count := utils.StrToInt(ctx.PostForm("count"))
	global.App.Log.Sugar().Infof("uid: %d, sku_id: %s, count: %s", uid, sku_id, count)

	// 校验数据
	var NewGoodsSKU model.GoodsSKU
	if ret := global.App.DB.Where("id = ?", sku_id).Find(&NewGoodsSKU); ret.RowsAffected == 0 {
		ctx.JSON(http.StatusOK, map[string]interface{}{"Code": 1, "errMsg": "商品不存在"})
		return
	}
	if count > NewGoodsSKU.Stock {
		ctx.JSON(http.StatusOK, map[string]interface{}{"Code": 2, "errMsg": "商品库存不足"})
		return
	}
	global.App.Log.Sugar().Infof("uid: %d, NewGoodsSKU: %v", uid, NewGoodsSKU)

	// 构建redis key
	cartKey := fmt.Sprintf("cartKey_%d", uid)
	global.App.RDB.HSet(ctx, cartKey, sku_id, count).Result()
	global.App.Log.Sugar().Infof("uid: %d 购物车数量更新成功", uid)

	ctx.JSON(http.StatusOK, map[string]interface{}{"Code": 3, "errMsg": "商品数量更新成功"})
}

func DeleteCart(ctx *gin.Context) { // 购物车的删除
	// 获取uid, sku_id
	uid := ctx.GetInt("uid")
	sku_id := ctx.PostForm("sku_id")

	// 校验数据
	var NewGoodsSKU model.GoodsSKU
	if ret := global.App.DB.Where("id = ?", sku_id).Find(&NewGoodsSKU); ret.RowsAffected == 0 {
		ctx.JSON(http.StatusOK, map[string]interface{}{"Code": 1, "errMsg": "商品不存在"})
		return
	}
	global.App.Log.Sugar().Infof("uid: %d, NewGoodsSKU: %v", uid, NewGoodsSKU)

	// 构建cartKey
	cartKey := fmt.Sprintf("cartKey_%d", uid)
	global.App.RDB.HDel(ctx, cartKey, sku_id).Result()
	global.App.Log.Sugar().Infof("uid: %d 购物车删除成功", uid)

	ctx.JSON(http.StatusOK, map[string]interface{}{"Code": 2, "errMsg": "删除商品成功"})
}
